package com.ibm.cognos.imt.fm

import com.ibm.cognos.imt.config.BiServerConfig
import ibm.cognos.imt.CogReport
import ibm.cognos.imt.DataItem
import ibm.cognos.imt.List
/**
 * Created by eric on 8/27/2014.
 */
class ExpressionRunner {
    BiServerConfig config;

    ExpressionRunner(BiServerConfig serverConfig) {
        config = serverConfig
    }

    public String generateSpec(String querystr) {
        if(isValidQuery(querystr)){

            CogReport report = new ListReport()
    //        report.setModelPath(config.getModelPath())
            report.setModelPath("/content/folder[@name='Samples']/folder[@name='Models']/package[@name='GO Sales (query)']/model[@name='model']")
            List list = report.list(parseQuery(querystr, report))
            report.setList(list)
            println("turn "+querystr+ " into "+report.getSpec())

            return setupFilters(querystr, report).getSpec();
    //        return report.getSpec()
        } else{
            return querystr;
        }
    }

    private boolean isValidQuery(String query) {
        return query.startsWith("{{")

    }

    private CogReport setupFilters(final String query, CogReport report) {
        def m = (query =~ /.when\((.*)\)/)
        def filters = []
        if(m.size()==1){
            String whenExp =  m[0][1]
            def filterStrs = whenExp.split("&&")
            filterStrs.each {
                def m1 = ( it =~ /(\[\w+\])}}(.+)/)
                filters << m1[0][1]+m1[0][2]
            }
        }
        println(filters)
        filters.each{
            report.filter(it)
        }
        return report;
    }

    private Collection parseQuery(final String queryStr, CogReport report) {
        def m = (queryStr =~ /\{\{([^\}\}]+)/ )
        def dataItems = []
        for (int i = 0; i < m.size(); i++) {
            def dataItem
            if(i==0){
                dataItem = report.dataItem(m[i][1]){
                    dataUsage = 'fact'
                    dataType = DataItem.DECIMAL
                    aggregate = "average"
                }
            }else{
                 dataItem = report.dataItem(m[i][1])
            }
            dataItems << dataItem
        }
        return dataItems
    }

    public static void main(String[] args) {
        String spec = new ExpressionRunner().generateSpec("{{[Sales (query)].[Sales].[Revenue]}}.when({{[Sales (query)].[Time].[Year]}}=2000&&{{[Sales (query)].[Branch].[Country]}}='china')")
        println(spec)
    }


}
